#!/bin/sh

# Start/stop/restart ices-cc as a daemon
# Copyright (c) 2011 Antonio Hernández Blas <hba.nihilismus@gmail.com>

#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#                    Version 2, December 2004
#
# Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
#
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long
# as the name is changed.
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
#  0. You just DO WHAT THE FUCK YOU WANT TO.
#

CONF='/etc/ices-cc.conf'
BASEDIR='/var/log/ices-cc'
CMMD="/usr/bin/ices-cc -B -c $CONF -D $BASEDIR"

ices_start() {
  if [ -x /usr/bin/ices-cc ]; then
    if [ -f $CONF ]; then
      PIDOF=$(pgrep -f "$CMMD")
      if [ ! -z "$PIDOF" ]; then
        echo "Error, ices is already running as daemon."
      else
        echo "Starting ices as daemon:  $CMMD"
        /bin/su - ices -c "$CMMD"
      fi
    else
      echo "Error, file $CONF does not exist."
    fi
  fi
}

ices_stop() {
  PIDOF=$(pgrep -f "$CMMD")
  if [ -z $PIDOF ]; then
    echo "Error, ices-cc is not running as daemon."
  else
    echo "Stoping ices-cc as daemon:  kill -s SIGINT $PIDOF"
    /bin/kill -s SIGINT $PIDOF
  fi
}

ices_status() {
  PIDOF=$(pgrep -f "$CMMD")
  if [ ! -z "$PIDOF" ]; then
    echo "ices-cc is running as daemon."
  else
    echo "ices-cc is not running as daemon."
  fi
}

case $1 in
  start)
    ices_start
  ;;
  stop)
    ices_stop
  ;;
  restart)
    ices_stop
    sleep 3
    ices_start
  ;;
  status)
    ices_status
  ;;
  *)
    echo "Usage $0 {start|stop|restart|status}"
    exit 1
  ;;
esac
